$(function () {
    var api_debug = false;

    $(".music_ctrl.on").click(function(){
        $(this).removeClass("on");
        $(this).addClass("off");
    });
    $(".music_ctrl.off").click(function(){
        $(this).addClass("on");
        $(this).removeClass("off");
    });
    $(".alert_cancel").click(function(){
        $(".win_alert").hide();
        //$(".mask").hide();
        if(typeof alertCb=="function"){
            alertCb();
        }
    });

    var alertCb;
    function alertTip(msg,cb){
        msg = msg||"未知错误";
        $("#alert_tip").html(msg);
        $(".win_alert").show();
        alertCb = cb;
        //$(".mask").show();
    }
    var storagePhone = localStorage.getItem("imusic_s09e01_phone");

    var phone_reg = "133|153|180|189|181|170|171|173|177|149".split("|");
    function inArray(s,arr){
        for(var i=0;i<arr.length;i++){
            if(s==arr[i]){
                return true;
            }
        }
        return false;
    }
    //document.addEventListener("touchmove",function(e){
    //    e.preventDefault();
    //    e.stopPropagation();
    //    return false;
    //},false);
    var SHAKE_THRESHOLD = 3000;
    var last_update = 0;
    var x, y, z, last_x = 0, last_y = 0, last_z = 0;
    var yaoyiyao_signal = 1;
    function deviceMotionHandler(eventData){
        var acceleration = eventData.accelerationIncludingGravity;
        var curTime = new Date().getTime();

        if ((curTime - last_update) > 100) {
            var diffTime = curTime - last_update;
            last_update = curTime;
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
            var status = document.getElementById("status");

            if (speed > SHAKE_THRESHOLD) {
                if(yaoyiyao_signal){
                    window.localStorage.setItem("yaoyiyao","1");
                    yaoyiyao_signal = 0;
                    setTimeout(function(){
                        window.localStorage.setItem("yaoyiyao","0");
                    },1000);
                    setTimeout(function(){
                        yaoyiyao_signal = 1;
                    },3000);
                }
            }
            last_x = x;
            last_y = y;
            last_z = z;
        }
    }
    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', deviceMotionHandler, false);
    }
    var originalHash = location.hash;
    $.ajax({
        url:auth_url+'?t='+new Date().getTime()+'&gamesRedirectUri='+encodeURIComponent(location.href.split('#')[0]),
        async:true,dataType:"json",type:"post",
        success:function(res){
            console.log('location.href',location.href);
            if(res.result === 'error'){
                console.log('login error', res.errmsg);
                location.href = res.url;
            }else if(res.result === 'unauth'){
                console.log('login unauth', res.url);
                location.href = res.url;
            }else{
                console.log('logined', res);
                console.log('current wechat user', res.user);
                //alertTip("user:"+JSON.stringify(res.user));
                nickname = res.user.name||res.user.nickname;
                mz_jwt = res.mz_jwt;
                window.localStorage.setItem("imusic_s09e01_mz_jwt",mz_jwt);
                window.localStorage.setItem("imusic_s09e01_nickname",nickname);
                initGameInfo();
            }
        },
        error:function(){
                //alertTip("user:"+JSON.stringify(res.user));
                nickname = "test";
                mz_jwt = "test";
                window.localStorage.setItem("imusic_s09e01_mz_jwt",mz_jwt);
                window.localStorage.setItem("imusic_s09e01_nickname",nickname);
                initGameInfo();
        }
    });

    $(".share_mask").click(function(){
        $(this).hide();
    });

    function wxJsSdk(){
        var url = "/auth/wechat/jssdk?originalUrl="+encodeURIComponent(location.href.split('#')[0])+'&datetime='+new Date().getTime();
        $.ajax({
            url:url,
            type:"get",
            dataType:"json",async:false,
            success:function(data){
                //alertTip(JSON.stringify(data))
                var jssdk = data.jssdk;
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: jssdk.appId, // 必填，公众号的唯一标识
                    timestamp: jssdk.timestamp, // 必填，生成签名的时间戳
                    nonceStr: jssdk.nonceStr, // 必填，生成签名的随机串
                    signature: jssdk.signature,// 必填，签名，见附录1
                    jsApiList: [
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo'
                    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                $(function(){
                    wx.ready(function() {
                        wxShareConfig();
                    });
                    wx.error(function (res) {
                        console.log(res.errMsg);
                    });
                })
            },
            error:function(){
                //alertTip("get jssdk fail:"+url);
            }
        });
    }
    var wxShareConfig = function(){
        wx.onMenuShareAppMessage({
            title: window["shareObj"].title,
            desc:  getShareDesc(),
            link:  getShareLink(),
            imgUrl:  window["shareObj"].iconstr,
            trigger: function (res) {
            },
            success: function (res) {
                //_czc.push(["_trackEvent", "分享", "share", "朋友", 1]);

            },
            cancel: function (res) {
            },
            fail: function (res) {
            }
        });
        //分享到朋友圈
        wx.onMenuShareTimeline({
            title: getShareDesc(),
            link:  getShareLink(),
            imgUrl:  window["shareObj"].iconstr,
            trigger: function (res) {
            },
            success: function (res) {
                //_czc.push(["_trackEvent", "分享", "share", "朋友圈", 1]);

            },
            cancel: function (res) {
            },
            fail: function (res) {
            }
        });
    };
    function getShareLink(){
        return location.href.split("startup.html")[0]+"startup.html#/game";
    }

    function getShareDesc(){
        var spend_time = localStorage.getItem("spend_time");
        if(spend_time){
            return "我仅用了"+Math.floor(spend_time)+"s便走出密室！你敢来挑战吗？";
        }
        return "据说只有十五年老歌迷才能走出这个密室哦……";
    }

    function initGameInfo(){
           document.body.style.display = "";
                if(originalHash==""||originalHash=="#/")
                    location.hash = "#/game";
                return;
        var mz_jwt = window.localStorage.getItem("imusic_s09e01_mz_jwt");
        $.ajaxSetup({
            beforeSend: function (xhr)
            {
                xhr.setRequestHeader("Authorization","Bearer "+mz_jwt);
            }
        });

        $.ajax({
            type : 'post',
            url : commonUrl + "/init",
            contentType : "application/json",
            async:false,
            dataType : 'json',
            success : function (data) {
                lotteryNum = data.lotteryNum;
                wxJsSdk();
                document.body.style.display = "";
                if(originalHash==""||originalHash=="#/")
                    location.hash = "#/game";
            },
            errof:function(){
                document.body.style.display = "";

            }
        });
    }

    var router = new Router({
        container: '#container',
        enterTimeout: 300,
        leaveTimeout: 300
    });

    var startup = {
        url: '/',
        className: 'startup',
        render: function () {
            return $('#tpl_startup').html();
        },
        bind:function(){

        }
    };
    // grid
    var home = {
        url: '/game',
        className: 'home',
        render: function () {
            return $('#tpl_home').html();
        }
    };
    var gameEnd = {
        url: '/game_end',
        className: 'game_end',
        render: function () {
            setTimeout(function(){
                var time = window.localStorage.getItem("spend_time");
                time = time||"0";
                time = Math.floor(time);
                $("#spend_time").html(time);
            },1000);
            return $('#tpl_game_end').html();
        },
        bind: function () {
            $('#container').on('click','.btn_go_share',function(){
                $(".share_mask").show();
            }).on('click', '.btn_go_lottery', function () {
                window.location.href = "#/lottery";
            });
        }
    };
    var lottery = {
        url: '/lottery',
        className: 'lottery',
        render: function () {
            setTimeout(function(){
                $(".rotate_light").show();
            },2000);
            return $('#tpl_lottery').html();
        },
        bind: function () {
            $('#container').on('click', '.logo', function () {
                $.ajax({
                    url:commonUrl+"/lottery",
                    type:"post",dataType:"json",
                    success:function(res){
                        //res = {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":2}};
                        //api_debug = 1;
                        if(api_debug){
                            var mockResult = [
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":1}},
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":2}},
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":3}},
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":4}},
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":5}},
                                {"success":true,"ret":1,"lotteryNum":4,"prize":{"prizeName":"爱音乐音乐盒","level":6}}
                            ];
                            var i = Math.floor(Math.random()*6);
                            res = mockResult[i];
                        }

                        //res.success = false;
                        //res = {success:false,msg:"您的抽奖机会已用完"}
                        if(!res.success){
                            $(".lottery div.rotate_light").hide();
                            $(".lottery div.logo").hide();
                            $(".lottery div.btn_rule").hide();
                            $(".lottery div.copyright").hide();
                            if(res.msg=="您的抽奖机会已用完"){
                                $(".btn_play_again").show();
                                $(".btn_go_share2").show();
                            }
                            alertTip(res.msg,function(){
                                $(".btn_play_again").hide();
                                $(".btn_go_share2").hide();
                                setTimeout(function(){
                                    $(".lottery div.rotate_light").show();
                                },2000);
                                $(".lottery div.logo").show();
                                $(".lottery div.btn_rule").show();
                                $(".lottery div.copyright").show();
                            });
                            return
                        }else{
                            //if(res.ret==0){
                            //    alertTip("未中奖");return;
                            //}
                            lottery.prize = res.prize;
                            lottery.lotteryNum = res.lotteryNum;
                            lottery.ret = res.ret;
                        }
                        $(".rotate_light").hide();
                        //console.log(res);
                        //$(".pkg_closed").hide();
                        //$(".pkg_opened").show();
                        $(".logo").css({background:" url(./images/app_logo2.png) no-repeat"});
                        $(".logo").addClass("fadeout");
                        setTimeout(function(){
                            window.location.href = "#/prize";
                        },1800);

                    },
                    error:function(){
                        alertTip("请求接口异常");
                    }
                });
            }).on('click', '.rule_return', function () {
                $('.rule').hide();
            }).on('click', '.rule_close', function () {
                $('.rule').hide();
            }).on('click','.btn_rule',function(){
                $('.rule').show();
            });
        }
    };
    var prize = {
        url: '/prize',
        className: 'prize',
        cb:function(rs){
            if(rs.success){
                var list = rs.data;
                var html = "";
                for(var i=0;i<list.length;i++){
                    var song = list[i].song;
                    var scroll = 0;
                    if(song.length>=12){
                        song += "&nbsp;&nbsp;&nbsp;&nbsp;"+song+"&nbsp;&nbsp;&nbsp;&nbsp;";
                        scroll = 1;
                    }
                    html += '<li data-resourceid="'+list[i].resource_id+'"><span>'+(i+1)+'.</span><span class="music_song"><span data-scroll="'+scroll+'">'+song+'</span></span><audio src="'+list[i].url+'" class="music_audio"></audio><span class="btn_play"></span></li>\n';
                }
                $("#music_box_list").html(html);

            }else{
                alertTip(rs.msg);
            }
        },
        render: function () {
            console.log(lottery);
            //api_debug = 1;
            if(api_debug){
                lottery.ret = 1;
                //lottery.prize = {"prizeName":"爱音乐音乐盒","level":2};
                lottery.prize = {"prizeName":"爱音乐钻石会员","level":1};
                //lottery.prize = {"prizeName":"爱音乐钻石会员","level":5};
                //lottery.prize = {"prizeName":"京东到家优惠券","level":3,"code":"aaaaattttt"};
            }
            setTimeout(function(){
                console.log("storagePhone",storagePhone);
                if(storagePhone){
                    $("input[placeholder='请输入天翼手机号码']").val(storagePhone);
                    $("#phone_balance").val(storagePhone);
                }
                if(lottery.ret==0||!lottery.ret){
                    //未中奖
                    $(".win_no_prize").show();
                }else {
                    var text1 = "";
                    var text2 = "";
                    var text3 = "";
                    lottery.prize = lottery.prize || {};
                    if (lottery.prize.level == 2) {

                        if(api_debug){
                            var rs = {"success":true,"data":[{"url":"./media/1688500597022600.wav","resource_id":2019500229,"song":"走着走着就散了(庄心妍)","singer":"庄心妍"},{"url":"http://3g.118100.cn/imsource?url=http://3partydl.imuapp.cn/res/thirdparty/V/2130/wav/50/82/62/2130508262022600.wav?deviceid=1000010406019&qd=5231","resource_id":2130508262,"song":"Always(太阳的后裔电视剧插曲)(尹美莱)","singer":"尹美莱"},{"url":"http://3g.118100.cn/imsource?url=http://3partydl.imuapp.cn/res/thirdparty/V/1688/wav/50/05/97/1688500597022600.wav?deviceid=1000010406019&qd=5231","resource_id":1688500597,"song":"问明月(青丘狐传说电视剧主题曲)(郁可唯)","singer":"郁可唯"},{"url":"http://3g.118100.cn/imsource?url=http://3partydl.imuapp.cn/res/thirdparty/V/2027/wav/50/01/14/2027500114022600.wav?deviceid=1000010406019&qd=5231","resource_id":2027500114,"song":"恋人心(魏新雨)","singer":"魏新雨"},{"url":"http://3g.118100.cn/imsource?url=http://3partydl.imuapp.cn/res/thirdparty/V/1013/wav/00/14/30/1013001430022600.wav?deviceid=1000010406019&qd=5231","resource_id":1013001430,"song":"演员(薛之谦)","singer":"薛之谦"}]};
                            prize.cb(rs);
                        }else{
                            $.ajax({
                                url:commonUrl+"/songs",type:"post",dataType:"json",data:{fromWechat:true},
                                success:prize.cb,
                                error:function(){
                                    alertTip("请求接口失败");
                                }
                            });
                        }

                        $(".win_music_box").show();
                    }
                    if (lottery.prize.level == 1) {
                        $(".prize_member").show();
                        $(".get_prize_validcode").html("验证码");
                        $(".win_get_prize").show();
                        $(".prize_cancel").css({color:"#ff6e2d"});
                    }
                    if (lottery.prize.level == 4) {
                        text1 = "10";
                        text2 = "M";
                        text3 = "三网流量";
                    }
                    if (lottery.prize.level == 5) {
                        text1 = "30";
                        text2 = "M";
                        text3 = "三网流量";
                    }
                    if (lottery.prize.level == 6) {
                        text1 = "30";
                        text2 = "元";
                        text3 = "三网话费";
                    }
                    if(lottery.prize.level == 3){
                        $(".code_num").html(lottery.prize.code);
                        $(".win_prize_code").show();
                    }
                    if (lottery.prize.level == 6 || lottery.prize.level == 4 || lottery.prize.level == 5) {
                        $(".get_prize_validcode").html(prize.randValidCode());
                        $(".prize_name").html('<b>'+text1+'</b>'+text2+'<span style="float: right;vertical-align: bottom;display: inline-block;margin-top: 28px;">'+text3+'</span>');
                        $(".prize_balance").show();
                        $(".win_get_prize").show();
                    }
                }
            },500);
            return $('#tpl_prize').html();
        },
        randValidCode:function(){
            return 1000+Math.floor(Math.random()*9000);
        },
        bind: function () {
            $('#container').on('click','.no_prize_return',function(){
                location.hash = "#/lottery";
            }).on('click','.show_member_rule',function(){
                $(".member_rule").show();
            }).on('click','.member_rule_return',function(){
                $(".member_rule").hide();
            }).on('click','.member_rule_close',function(){
                $(".member_rule").hide();
            }).on('click','.btn_music_list',function(){
                $(".win_music_box").show();
                $(".win_no_prize").hide();
                $.ajax({
                    url:commonUrl+"/songs",type:"post",dataType:"json",data:{fromWechat:true},
                    success:prize.cb,
                    error:function(){
                        alertTip("请求接口失败");
                    }
                });
            }).on('click','.btn_get_prize_success_share',function(){
                $(".share_mask").show();
            }).on('click','.code_usage',function(){
                $(".jd_usage_rule").show();
            }).on('click','.jd_rule_close',function(){
                $(".jd_usage_rule").hide();
            }).on('click','.jd_rule_return',function(){
                $(".jd_usage_rule").hide();
            }).on('click','.music_cancel',function(){
                $(".win_music_box>div").hide();
                $(".music_box").show();
            }).on('click','.btn_get_music_subscribe',function(){
                var phone = $("#phone_get_music").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".get_music_no_subscribe").hide();
                    alertTip("请输入电信号码",function(){
                        $(".get_music_no_subscribe").show();
                    });
                    return;
                }
                var code = $("#code_get_music").val();
                $.ajax({
                    url:commonUrl+"/openCrbt",data:{phone:phone,code:code,fromWechat:true},dataType:"json",type:"post",
                    success:function(rs){
                        if(api_debug){
                            rs = {success:true,msg:""}
                        }
                        if(rs.success){
                            $(".get_music_form").show();
                            $(".get_music_form").css({background:"url(./images/app_get_music2.png)",width:"482px"});
                            $(".get_music_no_subscribe").hide();
                        }else{
                            $(".get_music_no_subscribe").hide();
                            alertTip(rs.msg,function(){
                                $(".get_music_no_subscribe").show();
                            });
                            return;
                        }
                    },
                    error:function(){
                        alertTip("请求接口失败");
                    }
                })
            }).on('click','.btn_get_music_confirm',function(){
                var phone = $("#phone_get_music").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".get_music_confirm").hide();
                    alertTip("请输入电信号码",function(){
                        $(".get_music_confirm").show();
                    });
                    return;
                }
                var code = $("#code_get_music").val();
                $.ajax({
                    url:commonUrl+"/getMusicBox",type:"post",dataType:"json",
                    data:{phone:phone,code:code,fromWechat:true},
                    success:function(rs){
                        if(rs.success){
                            $(".get_music_confirm").hide()
                            $(".get_music_success").show();
                        }else{
                            $(".get_music_confirm").hide();
                            alertTip(rs.msg,function(){
                                $(".get_music_confirm").show();
                            });
                            return;
                        }
                    },
                    error:function(){
                        alertTip("请求接口失败");
                    }
                })
            }).on('click','.btn_get_music1',function(){
                $(".music_box").hide();
                $(".get_music_form").show();
            }).on('click','.btn_get_prize_success_confirm',function(){
                window.location.hash = "#/lottery";
            }).on('click','.btn_get_music',function(){

                var phone = $("#phone_get_music").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".get_music_form").hide();
                    alertTip("请输入电信号码",function(){
                        $(".get_music_form").show();
                    });
                    return;
                }
                var code = $("#code_get_music").val();
                var checked = $(".radio3")[0].getAttribute("data-status");
                if(checked=="0"){
                    $(".get_music_form").hide();
                    alertTip("请选择同意《会员服务条款》",function(){
                        $(".get_music_form").show();
                    });
                    return;
                }
                if(!code){
                    $(".get_music_form").hide();
                    alertTip("请输入验证码",function(){
                        $(".get_music_form").show();
                    });
                    return;
                }
                //判断是否彩铃用户
                $.ajax({
                    url:commonUrl+"/iscrbtuser",
                    type:"post",dataType:"json",data:{phone:phone},
                    success:function(rs){
                        if(api_debug){
                            rs = {success:true,iscrbtuser:true,msg:""}
                            //rs = {success:true,iscrbtuser:false,msg:""}
                        }
                        if(rs.success){
                            if(rs.iscrbtuser){
                                //已订购彩铃，弹出确认订购音乐盒
                                $(".get_music_form").hide();
                                $(".get_music_confirm").show();
                            }else{
                                //未订购彩铃
                                $(".get_music_form").hide();
                                $(".get_music_no_subscribe").show();
                            }
                        }else{
                            $(".win_music_box").hide();
                            alertTip(rs.msg,function(){
                                $(".win_music_box").show();
                            });
                            return;
                        }
                    },
                    error:function(){
                        alertTip("请求接口失败");

                    }
                })

            }).on('click','.sendValidCode_get_music',function(){
                if(prize.sending2){return;}
                if(this.innerHTML!="验证码")return;
                prize.sending2 = 1;
                var phone = $("#phone_get_music").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".win_music_box").hide();
                    alertTip("请输入电信号码",function(){
                        $(".win_music_box").show();
                    });
                    prize.sending2 = 0;
                    return;
                }
                $.ajax({
                    url:commonUrl+"/musicRandomCode",
                    type:"post",
                    data:{phone:phone,fromWechat:true},
                    success:function(rs){
                        if(api_debug){
                            rs = {success:true};
                        }
                        prize.tick2 = 60;
                        prize.sending2 = 0;
                        if(rs.success){
                            var n = setInterval(function(){
                                $(".sendValidCode_get_music").html(prize.tick2--);
                                if(prize.tick2<=-1){
                                    prize.sending2 = 0;
                                    $(".sendValidCode_get_music").html("验证码");
                                    clearInterval(n);
                                }
                            },1000);
                        }else{
                            $(".get_music_form").hide();
                            alertTip(rs.msg,function(){
                                $(".get_music_form").show();
                            });
                            return;
                        }
                        console.log(rs);
                    },
                    error:function(){
                        prize.sending2 = 0;
                        alertTip("请求接口失败");
                    }
                })
            }).on('click','.member_cancel',function(){
                $(".win_get_prize").show();
                $(".win_confirm_member").hide();
            }).on('click','.prize_cancel',function(){
                window.location.hash = "#/lottery";
            }).on('click', '.btn_get_prize', function () {
                var phone = "";
                if (lottery.prize.level == 6 || lottery.prize.level == 4 || lottery.prize.level == 5) {
                    phone = $("#phone_balance").val();
                    if(phone.length!=11){
                        $(".prize_balance").hide();
                        $(".btn_get_prize").hide();
                        alertTip("请输入正确的手机号码",function(){
                            $(".prize_balance").show();
                            $(".btn_get_prize").show();
                        });
                        return;
                    }
                    if($(".get_prize_validcode")[0].innerHTML!=$("#code_balance").val()){
                        $(".prize_balance").hide();
                        $(".btn_get_prize").hide();
                        alertTip("验证码错误",function(){
                            $(".prize_balance").show();
                            $(".btn_get_prize").show();
                        });
                        return;
                    }
                    $.ajax({
                        url:commonUrl+"/getPrize",
                        type:"post",
                        data:{phone:phone,fromWechat:true,prizeLevel:lottery.prize.level},
                        success:function(rs){
                            if(rs.success){
                                $(".win_get_prize").hide();
                                $(".get_prize_success").show();
                                localStorage.setItem("imusic_s09e01_phone",phone);
                            }else{
                                $(".prize_balance").hide();
                                $(".btn_get_prize").hide();
                                alertTip(rs.msg,function(){
                                    $(".prize_balance").show();
                                    $(".btn_get_prize").show();
                                });
                                return;
                            }
                        },
                        error:function(){
                            alertTip("请求接口失败");
                        }
                    })
                }
                if (lottery.prize.level == 1) {
                    var phone = $("#phone_member").val();
                    var code = $("#code_member").val();
                    var checked = $(".radio2")[0].getAttribute("data-status");
                    if(checked=="0"){
                        $(".prize_member").hide();
                        $(".btn_get_prize").hide();
                        alertTip("请选择同意《会员服务条款》",function(){
                            $(".prize_member").show();
                            $(".btn_get_prize").show();
                        });
                        return;
                    }
                    if(!code){
                        $(".prize_member").hide();
                        $(".btn_get_prize").hide();
                        alertTip("请输入验证码",function(){
                            $(".prize_member").show();
                            $(".btn_get_prize").show();
                        });
                        return;
                    }
                    if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                        $(".prize_member").hide();
                        $(".btn_get_prize").hide();
                        alertTip("请输入电信号码",function(){
                            $(".prize_member").show();
                            $(".btn_get_prize").show();
                        });
                        return;
                    }
                    $(".win_get_prize").hide();
                    $(".win_confirm_member").show();
                }

            }).on('click', '.btn_get_member_confirm', function () {
                var phone = $("#phone_member").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".win_confirm_member").hide();
                    alertTip("请输入电信号码",function(){
                        $(".win_confirm_member").show();
                    });
                    return;
                }
                var code = $("#code_member").val();
                $.ajax({
                    url:commonUrl+"/getMember",
                    type:"post",
                    data:{phone:phone,fromWechat:true,code:code},
                    success:function(rs){
                        //api_debug = false;
                        if(rs.success){
                            $(".win_confirm_member").hide();
                            $(".get_member_success").show();
                        }else{
                            $(".win_confirm_member").hide();
                            alertTip(rs.msg,function(){
                                $(".win_confirm_member").show();
                            });
                        }

                    },
                    error:function(){
                        alertTip("请求接口异常");
                    }
                })
            }).on('click','.btn_play',function(){
                var audios = $(".music_audio");
                for(var i=0;i<audios.length;i++){
                    audios[i].pause();
                }
                var audioEle = this.parentNode.childNodes[2];
                if(!audioEle.src){
                    audioEle.src = audioEle.getAttribute("data-src");
                }
                audioEle.play();
                clearInterval(prize.scrollSongInterval);
                $("span[data-scroll='1']").css({marginLeft:0});
                $(".btn_pause").addClass("btn_play");
                $(".btn_pause").removeClass("btn_pause");
                var songNameEle = this.parentNode.childNodes[1].childNodes[0];
                var scroll = songNameEle.getAttribute("data-scroll");
                if(scroll=="1"){
                    var n = 0;

                    prize.scrollSongInterval = setInterval(function(){
                        n--;
                        songNameEle.style.marginLeft = n+"px";
                        if(-n>(songNameEle.offsetWidth/2)){n=0;}
                    },20);
                }
                $(this).addClass("btn_pause");
            }).on('click','.btn_pause',function(){
                this.parentNode.childNodes[2].pause();

                $(this).addClass("btn_play");
                $(this).removeClass("btn_pause");
                clearInterval(prize.scrollSongInterval);
            }).on('click','.prize_radio',function(){
                console.log(this);
                var status = this.getAttribute("data-status");
                this.setAttribute("data-status",status=="0"?"1":"0");
            }).on('click','.sendValidCode',function(){
                if(prize.sending){return;}
                if($(".sendValidCode")[0].innerHTML!="验证码")return;
                prize.sending = 1;
                var phone = $("#phone_member").val();
                if(!inArray(phone.substr(0,3),phone_reg)||phone.length!=11){
                    $(".win_get_prize").hide();
                    alertTip("请输入电信号码",function(){
                        $(".win_get_prize").show();
                    });
                    prize.sending = 0;
                    return;
                }
                $.ajax({
                    url:commonUrl+"/memberRandomCode",
                    type:"post",
                    data:{phone:$("#phone_member").val(),fromWechat:true},
                    success:function(rs){
                        if(api_debug){
                            rs = {success:true};
                        }
                        prize.tick = 60;
                        prize.sending = 0;
                        if(rs.success){
                            var n = setInterval(function(){
                                $(".sendValidCode").html(prize.tick--);
                                if(prize.tick<=-1){
                                    prize.sending = 0;
                                    $(".sendValidCode").html("验证码");
                                    clearInterval(n);
                                }
                            },1000);
                        }else{
                            alertTip(rs.msg);
                            return;
                        }

                        console.log(rs);

                    },
                    error:function(){
                        prize.sending = 0;
                        alertTip("请求接口异常");
                    }
                })
            });
        }
    };
    // button
    var share = {
        url: '/share',
        className: 'share',
        render: function () {
            return $('#tpl_share').html();
        }
    };

    // cell
    var cell = {
        url: '/cell',
        className: 'cell',
        render: function () {
            return $('#tpl_cell').html();
        }
    };

    // toast
    var toast = {
        url: '/toast',
        className: 'toast',
        render: function () {
            return $('#tpl_toast').html();
        },
        bind: function () {
            $('#container').on('click', '#showToast', function () {
                $('#toast').show();
                setTimeout(function () {
                    $('#toast').hide();
                }, 2000);
            }).on('click', '#showLoadingToast', function () {
                $('#loadingToast').show();
                setTimeout(function () {
                    $('#loadingToast').hide();
                }, 2000);
            });
        }
    };

    // dialog
    var dialog = {
        url: '/dialog',
        className: 'dialog',
        render: function () {
            return $('#tpl_dialog').html();
        },
        bind: function () {
            $('#container').on('click', '#showDialog1', function () {
                $('#dialog1').show().on('click', '.weui_btn_dialog', function () {
                    $('#dialog1').off('click').hide();
                });
            }).on('click', '#showDialog2', function () {
                $('#dialog2').show().on('click', '.weui_btn_dialog', function () {
                    $('#dialog2').off('click').hide();
                });
            });

        }
    };

    // progress
    var progress = {
        url: '/progress',
        className: 'progress',
        render: function () {
            return $('#tpl_progress').html();
        },
        bind: function () {
            console.log("progress bind");
            $('#container').on('click', '#btnStartProgress', function () {
                if ($(this).hasClass('weui_btn_disabled')) {
                    return;
                }

                $(this).addClass('weui_btn_disabled');

                var progress = 0;
                var $progress = $('.js_progress');

                function next() {
                    $progress.css({width: progress + '%'});
                    progress = ++progress % 100;
                    setTimeout(next, 30);
                }

                next();
            });
        }
    };

    // msg
    var msg = {
        url: '/msg',
        className: 'msg',
        render: function () {
            return $('#tpl_msg').html();
        }
    };

    // article
    var article = {
        url: '/article',
        className: 'article',
        render: function () {
            return $('#tpl_article').html();
        }
    };

    // actionsheet
    var actionsheet = {
        url: '/actionsheet',
        className: 'actionsheet',
        render: function () {
            return $('#tpl_actionsheet').html();
        },
        bind: function () {
            $('#container').on('click', '#showActionSheet', function () {
                var mask = $('#mask');
                var weuiActionsheet = $('#weui_actionsheet');
                weuiActionsheet.addClass('weui_actionsheet_toggle');
                mask.show().addClass('weui_fade_toggle').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                $('#actionsheet_cancel').one('click', function () {
                    hideActionSheet(weuiActionsheet, mask);
                });
                weuiActionsheet.unbind('transitionend').unbind('webkitTransitionEnd');

                function hideActionSheet(weuiActionsheet, mask) {
                    weuiActionsheet.removeClass('weui_actionsheet_toggle');
                    mask.removeClass('weui_fade_toggle');
                    weuiActionsheet.on('transitionend', function () {
                        mask.hide();
                    }).on('webkitTransitionEnd', function () {
                        mask.hide();
                    })
                }
            });
        }
    };

    // icons
    var icons = {
        url: '/icons',
        className: 'icons',
        render: function () {
            return $('#tpl_icons').html();
        }
    };

    // panel
    var panel = {
        url: '/panel',
        className: 'panel',
        render: function () {
            return $('#tpl_panel').html();
        }
    };

    // tab
    var tab = {
        url: '/tab',
        className: 'tab',
        render: function () {
            return $('#tpl_tab').html();
        }
    };

    // navbar
    var navbar = {
        url: '/navbar',
        className: 'navbar',
        render: function () {
            return $('#tpl_navbar').html();
        }
    };

    // tabbar
    var tabbar = {
        url: '/tabbar',
        className: 'tabbar',
        render: function () {
            return $('#tpl_tabbar').html();
        }
    };

    // searchbar
    var searchbar = {
        url: '/searchbar',
        className: 'searchbar',
        render: function () {
            return $('#tpl_searchbar').html();
        },
        bind: function () {
            $('#container').on('focus', '#search_input', function () {
                var $weuiSearchBar = $('#search_bar');
                $weuiSearchBar.addClass('weui_search_focusing');
            }).on('blur', '#search_input', function () {
                var $weuiSearchBar = $('#search_bar');
                $weuiSearchBar.removeClass('weui_search_focusing');
                if ($(this).val()) {
                    $('#search_text').hide();
                } else {
                    $('#search_text').show();
                }
            }).on('input', '#search_input', function () {
                var $searchShow = $("#search_show");
                if ($(this).val()) {
                    $searchShow.show();
                } else {
                    $searchShow.hide();
                }
            }).on('touchend', '#search_cancel', function () {
                $("#search_show").hide();
                $('#search_input').val('');
            }).on('touchend', '#search_clear', function () {
                $("#search_show").hide();
                $('#search_input').val('');
            });
        }
    };

    router.push(home)
        .push(share)
        .push(cell)
        .push(toast)
        .push(dialog)
        .push(progress)
        .push(msg)
        .push(article)
        .push(actionsheet)
        .push(icons)
        .push(panel)
        .push(tab)
        .push(navbar)
        .push(tabbar)
        .push(searchbar)
        .push(lottery)
        .push(gameEnd)
        .push(prize)
        .push(startup)
        .setDefault('/')
        .init();


    // .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
    // 相关 issue: https://github.com/weui/weui/issues/15
    // 解决方法:
    // 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
    // 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
    //    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
    if (/Android/gi.test(navigator.userAgent)) {
        window.addEventListener('resize', function () {
            if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                window.setTimeout(function () {
                    document.activeElement.scrollIntoViewIfNeeded();
                }, 0);
            }
        })
    }
});